//
// Created by THE13 on 2024/2/5.
//
#include "sdl2_interface.h"
#include "st7789.h"

sdl2_t sdl2= {0};

/*__attribute__((section(".data")))*/ uint16_t disp_buf[SCREEN_HEIGHT][SCREEN_WIDTH];

//反色 Inverse color
int XorColor(int color)
{
    int xorColor = color;
    xorColor =WHITE^color;
		xorColor = (xorColor>>8)|(xorColor<<8);
		return xorColor;
}

//透明 transparent color
uint16_t TraColor(uint16_t color)
{
    float alpha = 0.5;//透明度
    uint16_t traColor = color;

    //前景色
    uint16_t foreground_color = sdl2.draw_color;
    //背景色
    traColor = (color<<8)|(color>>8);//高低位反转


    uint16_t red1 = (traColor >> 11) & 0x1F;
    uint16_t green1 = (traColor >> 5) & 0x3F;
    uint16_t blue1 = traColor & 0x1F;

    uint16_t red2 = (foreground_color >> 11) & 0x1F;
    uint16_t green2 = (foreground_color >> 5) & 0x3F;
    uint16_t blue2 = foreground_color & 0x1F;

    uint16_t redout   = (red1   * (1-alpha) + (red2   * alpha));
    uint16_t greenout = (green1 * (1-alpha) + (green2 * alpha));
    uint16_t blueout  = (blue1  * (1-alpha) + (blue2  * alpha));


    traColor =( (redout<<11) | (greenout<<6) | (blueout) );

    traColor = (traColor>>8)|(traColor<<8);//高低位反转

    return traColor;
}



//对单个像素操作
uint16_t sdl2_setPixBuffer(sdl2_t *sdl2,int x0,int y0)
{
    //1.check the state:if out of the range , don't operate the buffer;
    if((x0>=SCREEN_WIDTH)||(x0<0)||(y0>=SCREEN_HEIGHT)||(y0<0)) return 0;
    //2.operate the buffer;
    if(sdl2 ->mode == NORMAL){//Draw the color
        disp_buf[y0][x0] = (sdl2->draw_color>>8)|(sdl2->draw_color<<8);
        return disp_buf[y0][x0];
    }
    if(sdl2->mode == XOR){//Inverse the color
        disp_buf[y0][x0] = XorColor(disp_buf[y0][x0]);
        return disp_buf[y0][x0];
    }
    if(sdl2->mode == TRA){//Transparent the color
        disp_buf[y0][x0] = TraColor(disp_buf[y0][x0]);
        return disp_buf[y0][x0];
    }
    return 0;//return error
}

void sdl2_setMode(sdl2_t *sdl2,uint8_t mode)
{
    sdl2->mode = mode;
}

void sdl2_setPencil(sdl2_t *sdl2,int draw_color,int bg_color)
{
    sdl2->draw_color = draw_color;
    sdl2->bg_color   = bg_color;
}

void sdl2_cleanBuffer(void)
{
    memset(disp_buf, WHITE, sizeof(disp_buf));
}


//给消失动画用的，10是页面消失动画帧数
#define PAGE_DISAPPEAR_FPS 10
void sdl2_GradualCleanBuffer(void)
{
	static	uint8_t  interval = PAGE_DISAPPEAR_FPS;
	if(interval!=0)
	{
    for (int i = 0; i < SCREEN_HEIGHT; i++) {
        for (int j = 0; j < SCREEN_WIDTH; j++) {
					if (i % interval == 0) {
            if (j % interval == 0) {
                disp_buf[i][j] = WHITE;
            }
					}
        }
    }
	}
	else
	{
		memset(disp_buf, WHITE, sizeof(disp_buf));
	}
		interval --;
		if(interval ==0)interval =PAGE_DISAPPEAR_FPS;
}

void sdl2_DrawPixel_buffer(sdl2_t *sdl2,uint16_t x, uint16_t y)
{
    sdl2_DrawHVLine(sdl2, x,  y,  1,  0);
}

//TODO: 配置外设驱动，将缓存区的数据发送出去
void sdl2_sendbuffer(void)
{
    ST7789_WriteData_Step1((uint8_t *)disp_buf);
}

